package com.example.myapplication

import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Configuration
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.setFragmentResult
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.cardgame.model.CardMatchingGame


// 游戏对象，初始化 24 张卡牌（两张匹配）
var game1: CardMatchingGame = CardMatchingGame(24)

// Fragment 实现另一种匹配规则的卡牌游戏界面
class FourthFragment : Fragment(), View.OnClickListener {

    lateinit var adapter: CardAdapter  // RecyclerView 适配器

    @SuppressLint("MissingInflatedId")
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // 加载布局文件
        val view = inflater.inflate(R.layout.activity_forth, container, false)

        // 初始化 RecyclerView
        val recyclerView: RecyclerView = view.findViewById(R.id.recyclerView)
        adapter = CardAdapter(game1)
        recyclerView.adapter = adapter

        // 根据屏幕方向设置网格列数
        val configure = resources.configuration
        recyclerView.layoutManager = if (configure.orientation == Configuration.ORIENTATION_PORTRAIT) {
            GridLayoutManager(context, 4)  // 竖屏 4 列
        } else {
            GridLayoutManager(context, 6)  // 横屏 6 列
        }

        // 设置点击监听：点击卡牌执行游戏逻辑并刷新 UI
        adapter.setOnClickListener { position ->
            game1.chooseCardAtIndex(position,3) // 两张牌匹配
            updateUI()
        }

        // 返回按钮
        val back = view.findViewById<Button>(R.id.button_back)
        back.setOnClickListener {
            Log.d("FourthFragment", "Score to send: ${game1.score}")

            // 保存分数到 SharedPreferences（可选，持久化）
            val sharedPreferences = activity?.getSharedPreferences("game_prefs", Context.MODE_PRIVATE)
            sharedPreferences?.edit()?.putInt("fourth_fragment_score", game1.score)?.apply()

            // 将分数通过 FragmentResult 传回上一个 Fragment
            setFragmentResult("requestKey", Bundle().apply {
                putString(SCORE, game1.score.toString())
            })

            // 返回上一个 Fragment
            activity?.supportFragmentManager?.popBackStack()
        }

        // 初始化 UI
        updateUI()

        // 重置游戏按钮
        val reset = view.findViewById<Button>(R.id.button19)
        reset.setOnClickListener {
            game1.reset()  // 重置游戏数据
            updateUI()     // 刷新 UI
        }

        return view
    }

    // 刷新界面：更新 RecyclerView 并显示分数
    fun updateUI() {
        adapter.notifyDataSetChanged()  // 通知 RecyclerView 数据改变
        val score = view?.findViewById<TextView>(R.id.textView)
        score?.text = "分数：${game1.score}"  // 更新分数显示
    }

    override fun onClick(p0: View?) {
        // TODO: 实现点击事件处理，如有需要
    }

    companion object {
        // 创建 Fragment 实例
        fun newInstance(): FourthFragment {
            return FourthFragment()
        }
    }
}
